package cn.stronglink.asset.message.mq.dam;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.Message;
import javax.jms.MessageListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.stronglink.asset.module.dam.interfaces.RealtimeDatasHandleStrategyI;
import cn.stronglink.asset.module.dam.service.RealTimeSendCmdToDam;
import cn.stronglink.asset.module.dam.service.RealTimeSendToDoorDb;
import cn.stronglink.asset.module.dam.service.RealTimeSendToSenDb;
import cn.stronglink.asset.module.dam.utils.dataJsonUtils.realtime.receive.IntercepterRealTimeDatasUtil;
import cn.stronglink.asset.module.dam.utils.dataJsonUtils.realtime.receive.SendDoorCmdToDamUtil;

/**
 * 监听Mq: damToweb消息, 调用内部线程类:处理数据
 */
@Component("realTimemsgReceive")
public class RealTimeDatasMsgReceiver  implements MessageListener {
	protected final Logger logger = LoggerFactory.getLogger(RealTimeDatasMsgReceiver.class);
	private List<RealtimeDatasHandleStrategyI> strategys = new ArrayList<RealtimeDatasHandleStrategyI>();
	private ExecutorService threadPool = Executors.newFixedThreadPool(100);// 线程数为100；

	// dam更新： 6个传感器数据   其他常量机柜信息
	@Autowired
	private RealTimeSendCmdToDam toDamCmd6Service;
	
	// db更新
	@Autowired
	private RealTimeSendToSenDb toSensorDbService;
	@Autowired
	private RealTimeSendToDoorDb toDoorDbService;
	
	
	@Override
	public void onMessage(Message message) {
		if (IntercepterRealTimeDatasUtil.isDataGood(message, 500)==false)
			return; // 两次门数据：1s间隔
		
		if(IntercepterRealTimeDatasUtil.doorFlag)//发送门状态指令
			SendDoorCmdToDamUtil.handleDamDatas(IntercepterRealTimeDatasUtil.doorDatas);
		
		if (strategys.isEmpty()) {
			strategys.add(toSensorDbService);
			strategys.add(toDamCmd6Service);
		}

		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				handle(IntercepterRealTimeDatasUtil.doorFlag);
			}
		});
	}

	// 逻辑处理
	public void handle(boolean isDoor) {
		if(isDoor) {
			//传感器数据
			toDoorDbService.handleDamDatas(IntercepterRealTimeDatasUtil.doorDatas);
		}
		else {
			for (RealtimeDatasHandleStrategyI ser : strategys) {
			
					ser.handleDamDatas(IntercepterRealTimeDatasUtil.senDatas);
					// super.excuteThread(new ThreadForReceiveUtil(realDatas, ser));
//					try {
//						Thread.sleep(10000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
			}
		}
	}
}
